package com.kgc.scd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.kgc.scd.constant.AliyunConstant;
import com.kgc.scd.service.SmsService;
import com.kgc.scd.util.ResultBuildUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created On : 2022/11/14.
 * <p>
 * Author : 刘慧枫
 * <p>
 * Description: 短信接口实现类
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Override
    public boolean sendMessage(Map<String, Object> map, String phone) {

        DefaultProfile profile =
                DefaultProfile.getProfile(AliyunConstant.REGION_ID, AliyunConstant.ACCESS_KEY_ID, AliyunConstant.SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试"); // 短信签名
        request.setTemplateCode("SMS_154950909"); // 短信模板code
        request.setPhoneNumbers(phone); // 测试号的号码（其它号码需要添加测试号先）
        request.setTemplateParam(JSONObject.toJSONString(map)); // 发送短信信息内容（因为这里是验证码，格式为：{"code":"4-6位数字"}）

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            log.info(JSON.toJSONString(response));
            return response.getMessage().equals("OK"); // 短信发送成功时Message信息为OK（默认的）
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            log.error("ErrCode:" + e.getErrCode());
            log.error("ErrMsg:" + e.getErrMsg());
            log.error("RequestId:" + e.getRequestId());
        }
        return false;
    }
}
